package com.apobates.forum.thrones.tag;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.apobates.forum.utils.Commons;

/**
 * Showing {1} to {10} of {57｝ entries
 *
 * @since 20171214
 * @author xiaofanku@live.cn
 */
public class PaginationCollectTag extends SimpleTagSupport {
    // 总记录数(必需)
    private int total;
    // 可以从地址中获取页码值的参数名(可选)
    private String pageName = "p";
    // 页码值,可以手动传入或者使用name从request中获取(可选)
    private Integer page;
    // 每页显示的记录数(可选)
    private Integer pageSize;
    // 可以从地址中获取每页显示数量值的参数名(可选)
    private String pageSizeName = "number";
    private final static Logger logger = LoggerFactory.getLogger(PaginationCollectTag.class);
    
    public void setTotal(int total) {
        this.total = total;
    }
    
    public void setPage(int page) {
        this.page = page;
    }
    
    @Override
    public void doTag() throws JspException, IOException {
        PageContext pc = (PageContext) getJspContext();
        HttpServletRequest request = (HttpServletRequest) pc.getRequest();
        if (null == page && !pageName.isEmpty()) {
            String pageNumeric = request.getParameter(pageName);
            if (Commons.isNotBlank(pageNumeric) && Commons.isNumeric(pageNumeric)) {
                page = Integer.valueOf(pageNumeric);
            }
        }
        if (null == pageSize && !pageSizeName.isEmpty()) {
            String pageNumber = request.getParameter(pageSizeName);
            if (Commons.isNotBlank(pageNumber) && Commons.isNumeric(pageNumber)) {
                pageSize = Integer.valueOf(pageNumber);
            }
        }
        if (null == page || null == pageSize) {
            if (logger.isDebugEnabled()) {
                logger.debug("[PTC]汇总分页信息失败");
            }
            getJspContext().getOut().print("");
            return;
        }
        // 输出
        int showMaxRecord = (page * pageSize);
        if (showMaxRecord > total) {
            showMaxRecord = total;
        }
        getJspContext().setAttribute("tagPageTotal", total);
        getJspContext().setAttribute("tagPageMinId", ((page - 1) * pageSize + 1));
        getJspContext().setAttribute("tagPageMaxId", showMaxRecord);
        
        // 输出标签体
        getJspBody().invoke(null);
    }
    
    public void setPageName(String pageName) {
        this.pageName = pageName;
    }
    
    public void setPage(Integer page) {
        this.page = page;
    }
    
    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }
    
    public void setPageSizeName(String pageSizeName) {
        this.pageSizeName = pageSizeName;
    }
}